package com.open.capacity.finance.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.open.capacity.finance.dao.AuditAnalysisDao;
import com.open.capacity.finance.dao.SourceBaseAssetDao;
import com.open.capacity.finance.dto.AuditModelBaseResult;
import com.open.capacity.finance.dto.audit_model_25.AuditModelResult;
import com.open.capacity.finance.dto.audit_model_25.AuditModelStep1;
import com.open.capacity.finance.dto.audit_model_25.AuditModelStep2;
import com.open.capacity.finance.dto.audit_model_25.ExcelData;
import com.open.capacity.finance.entity.AuditModel;
import com.open.capacity.finance.entity.AuditModelRule;
import com.open.capacity.finance.service.AbstractAuditMakeResultFactory;
import com.open.capacity.finance.service.AuditModelRuleService;
import com.open.capacity.finance.service.AuditModelService;
import com.open.capacity.finance.util.FileUtil;
import com.open.capacity.model.system.SysUser;
import com.open.capacity.nk.entity.AaDepartment;
import com.open.capacity.nk.service.AaDepartmentService;
import com.open.capacity.nk.service.AaPersonService;
import com.open.capacity.user.service.SysUserService;
import com.open.capacity.utils.StringUtil;
import com.open.capacity.utils.encrypt.Md5Utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.list.AbstractLinkedList;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class AuditModelActuator25ServiceImpl<T extends AuditModelBaseResult> extends AbstractAuditMakeResultFactory {

    @Autowired
    private AuditAnalysisDao analysisDao;

    @Autowired
    private AuditModelRuleService ruleService;

    @Autowired
    private AuditModelService modelService;

    @Autowired
    private SysUserService userService;

    @Autowired
    private AaPersonService personService;

    @Autowired
    private AaDepartmentService departmentService;

    @Autowired
    private SourceBaseAssetDao assetDao;


    @Override
    protected T analyseResultData(String modelId, Map param) {
        String companyId = param.containsKey("companyId") ? param.get("companyId").toString() : "";
        AuditModelResult result = new AuditModelResult();
        AuditModel model = modelService.findById(modelId);
        Assert.notNull(model, "找不到该模型");
        List<AuditModelRule> rules = ruleService.findByModelId(modelId);

        rules.forEach(t -> {
            if (t.getConfKey().equals("categoryNames")) {
                param.put(t.getConfKey(), t.getConfValue().split(","));
            } else {
                param.put(t.getConfKey(), t.getConfValue());
            }
        });
        result.setModelName(model.getCodeAndName());
        param.remove("kjnd");
        List<AuditModelStep1> step1List = assetDao.getDepartmentData(param);
        List<AuditModelStep2> step2List = new ArrayList<>();
        Map<String, Object> params = new HashMap<>();

        for (AuditModelStep1 item : step1List) {
            params.put("departmentId", item.getDepartmentId());
//TODO 临时取数            Integer userCount =   personService.countByDepartment(item.getCompanyId(), item.getDepartmentId(), item.getDepartmentName());

            Map<String, Object> p = new HashMap();
            p.put("companyId", item.getCompanyId());
            p.put("name", item.getDepartmentName());
            List<AaDepartment> departmentList = departmentService.findAll(p);
            Integer userCount = 0;
            if (CollectionUtils.isNotEmpty(departmentList)) {
                userCount = departmentList.get(0).getPersonCount() == null ? 0 : departmentList.get(0).getPersonCount();
            }

            item.setPersonCount(userCount);
            if (item.getDeviceCount() != null && userCount > 0) {
                item.setPerDeviceCount(new BigDecimal((float) item.getDeviceCount() / item.getPersonCount()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
            }

            Optional<AuditModelStep2> optional = step2List.stream().filter(t -> t.getCompanyId().equals(item.getCompanyId()) && t.getCategoryName().equals(item.getCategoryName())).findFirst();
            if (optional.isPresent()) {
                optional.get().setDeviceCount((optional.get().getDeviceCount() == null ? 0 : optional.get().getDeviceCount()) + (item.getDeviceCount() == null ? 0 : item.getDeviceCount()));
// TODO 临时取数               optional.get().setPersonCount(personService.countByCompany(item.getCompanyId()));
                optional.get().setPersonCount(optional.get().getPersonCount() + userCount);
                if (optional.get().getPersonCount() > 0) {
                    optional.get().setPerDeviceCount(new BigDecimal((float) optional.get().getDeviceCount() / optional.get().getPersonCount()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                }
            } else {
                AuditModelStep2 step2 = new AuditModelStep2();
                step2.setCompanyId(item.getCompanyId());
                step2.setCompanyName(item.getCompanyName());
                step2.setCategoryName(item.getCategoryName());
                step2.setDeviceCount((step2.getDeviceCount() == null ? 0 : step2.getDeviceCount()) + (item.getDeviceCount() == null ? 0 : item.getDeviceCount()));
                step2.setPersonCount((step2.getPersonCount() == null ? 0 : step2.getPersonCount()) + (item.getPersonCount() == null ? 0 : item.getPersonCount()));
                if (step2.getPersonCount() > 0) {
                    step2.setPerDeviceCount(new BigDecimal((float) step2.getDeviceCount() / step2.getPersonCount()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                }
                step2List.add(step2);
            }
        }

        result.setCompanyId(companyId);
        result.setStep1List(step1List);
        result.setStep2List(step2List);
        if (CollectionUtils.isEmpty(step1List)) {
            result.setExists(0);
        } else {
            result.setExists(1);

            //持久化本地
            persistence(result);
        }

        return (T) result;
    }

    @Override
    protected int persistence(AuditModelBaseResult data) {
        int result = 0;

        String content = JSON.toJSONString(data, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteDateUseDateFormat);

        data.setResultFileMd5(Md5Utils.hash(content));
        data.setResultFileUrl("/upload/analyse/model25_" + data.getCompanyId() + "_" + data.getResultFileMd5() + ".json");

        Writer write = null;
        try {
            File file = new File(fileuploadPath + "/upload/analyse/model25_" + data.getCompanyId() + "_" + data.getResultFileMd5() + ".json");
            if (file.exists()) {
                file.delete();
            }
            file.createNewFile();
            // 写入文件
            write = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8);
            write.write(content);
            write.flush();
            write.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                write.close();
            } catch (IOException e) {
                log.error(e.getMessage());
            }
        }
        return result;
    }

    @Override
    public T getData(String modelId, Map param) {
        return analyseResultData(modelId, param);
    }


    /**
     * 从本地加载数据
     */
    public AuditModelBaseResult getDataFromJson(String jsonUrl, Map param) {
        AuditModelResult result = null;
        try {
            String json = FileUtil.readTxtToJson(fileuploadPath + jsonUrl);
            result = JSONObject.parseObject(json, new TypeReference<AuditModelResult>() {
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        filterCondition(result, param);

        return result;
    }

    /**
     * 本地json数据条件过滤
     */
    private AuditModelResult filterCondition(AuditModelResult orig, Map param) {
        AuditModelResult result = orig;
        String companyId = MapUtils.getString(param, "companyId");
        String categoryName = MapUtils.getString(param, "categoryName");
        String departmentName = MapUtils.getString(param, "departmentName");

        List<AuditModelStep1> list = orig.getStep1List();
        if (StringUtil.isNotEmpty(companyId)) {
            list = list.stream().filter(t -> t.getCompanyId().equals(companyId)).collect(Collectors.toList());
        }
        if (StringUtil.isNotEmpty(categoryName)) {
            list = list.stream().filter(t -> t.getCategoryName().contains(categoryName)).collect(Collectors.toList());
        }
        if (StringUtil.isNotEmpty(departmentName)) {
            list = list.stream().filter(t -> t.getDepartmentName().contains(departmentName)).collect(Collectors.toList());
        }
        result.setStep1List(list);

        return result;
    }

    public void exportExcel(String modelId, Map params, HttpServletResponse response) {
        AuditModelResult t = (AuditModelResult) analyseResultData(modelId, params);

        export(t, response);
    }

    @Override
    public void exportExcelFromJson(String modelId, String jsonUrl, HttpServletResponse response) {
        AuditModelResult t = null;
        try {
            String json = FileUtil.readTxtToJson(fileuploadPath + jsonUrl);
            t = JSONObject.parseObject(json, new TypeReference<AuditModelResult>() {
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

        export(t, response);
    }

    private void export(AuditModelResult t, HttpServletResponse response) {
        List<ExcelData> result = t.getStep1List().stream().map(item -> {
            ExcelData model = new ExcelData();
            BeanUtils.copyProperties(item, model);
            return model;
        }).collect(Collectors.toList());

        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment;filename=download_25.xls");
        OutputStream ouputStream = null;
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(),
                ExcelData.class, result);
        try {
            ouputStream = response.getOutputStream();
            workbook.write(ouputStream);
        } catch (Exception e) {
            throw new RuntimeException("系统异常");
        } finally {
            try {
                if (ouputStream != null) {
                    ouputStream.flush();
                    ouputStream.close();
                }
            } catch (Exception e) {
                throw new RuntimeException("系统异常");
            }
        }
    }
}
